<!--
 * @Description: 施工进度总计划详情
 * @Author: wind-lc
 * @version: 1.0 
 * @Date: 2021-11-16 19:41:11
 * @LastEditTime: 2023-07-05 11:23:43
 * @FilePath: \cscec-pms-admin\src\views\construction\contractor\components\PlanBoardDetail.vue
-->
<template>
  <div
    v-show="visible"
    class="plan-board-detail"
  >
    <div class="btn-wrapper">
      <a-button
        type="primary"
        :disabled="loading"
        @click="ganttVisible = true"
      >
        查看甘特图
      </a-button>
      <a-button
        type="primary"
        :disabled="loading"
        @click="$refs.table.setAllTreeExpansion()"
      >
        展开全部
      </a-button>
      <a-button
        type="primary"
        :disabled="loading"
        @click="$refs.table.clearTreeExpand()"
      >
        收起全部
      </a-button>
      <span>附件：</span>
        <upload-list
          :edit-model="2"
          style="margin:5px 0;"
          disabled
          :is-close="false"
          :show-upload="false"
          :upload-arrys.sync="fileList"
        />
    </div>
    <div class="pub-table-select-count">
      <a-icon
        type="info-circle"
        theme="twoTone"
      />
      <span>
        项目：<span class="totalNum">{{ tableInfo.projectName }}</span>
      </span>
      <span>
        节点共 <span class="totalNum">{{ tableInfo.nodeTotalNum }}</span> 项
      </span>
      <span>
        一级节点共 <span class="totalNum">{{ tableInfo.firstNodeNum }}</span> 项
      </span>
      <span>
        二级节点共 <span class="totalNum">{{ tableInfo.secondNodeNum }}</span> 项
      </span>
      <span>
        三级节点共 <span class="totalNum">{{ tableInfo.threeNodeNum }}</span> 项
      </span>
      <span>
        周期天数 <span class="totalNum">{{ tableInfo.periodDay }}</span> 天
      </span>
      <span>
        周期间隔 <span class="totalNum">{{ tableInfo.periodDate }}</span>
      </span>
    </div>
    <!-- 搜索 -->
    <a-form-model
      :model="searchForm"
      layout="inline"
      class="plan-board-detail-search"
    >
      <a-form-model-item>
        <b>搜索:</b>
      </a-form-model-item>
      <a-form-model-item>
        <a-input
          v-model="searchForm.businessMatters"
          placeholder="节点名称"
          class="plan-board-detail-search-width"
        />
      </a-form-model-item>
      <a-form-model-item>
        <a-select
          v-model="searchForm.nodeControl"
          placeholder="节点管控级别"
          class="plan-board-detail-search-width"
          allowClear
        >
          <a-select-option
            v-for="item in nodeControlLevelList"
            :key="item.value"
            :value="item.value"
          >
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item>
        <a-range-picker
          v-model="searchForm.planStart"
          class="plan-board-detail-search-date"
          :placeholder="['计划开始时间起','计划开始时间止']"
        />
      </a-form-model-item>
      <a-form-model-item>
        <a-range-picker
          v-model="searchForm.planEnd"
          class="plan-board-detail-search-date"
          :placeholder="['计划完成时间起','计划完成时间止']"
        />
      </a-form-model-item>
      <a-form-model-item>
        <a-range-picker
          v-model="searchForm.completeDate"
          class="plan-board-detail-search-date"
          :placeholder="['实际完成时间起','实际完成时间止']"
        />
      </a-form-model-item>
      <a-form-model-item>
        <a-select
          v-model="searchForm.isVerticalTransportNode"
          placeholder="是否垂直运输设备装拆"
          class="plan-board-detail-search-width"
          allowClear
        >
          <a-select-option :value="'false'">
            否
          </a-select-option>
          <a-select-option :value="'true'">
            是
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item>
        <a-select
          v-model="searchForm.workStatus"
          placeholder="节点状态"
          class="plan-board-detail-search-width"
          allowClear
        >
          <a-select-option
            v-for="item in nodeStatusList"
            :key="item.value"
            :value="item.value"
          >
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item>
        <a-button
          type="primary"
          :loading="loading"
          @click="loadData(true)"
        >
          搜索
        </a-button>
        <a-button
          :disabled="loading"
          class="ml12"
          @click="handleReset"
        >
          重置
        </a-button>
      </a-form-model-item>
    </a-form-model>
    <!-- 搜索 -->
    <a-spin :spinning="loading">
      <u-table
        ref="table"
        fixed-columns-roll
        :height="500"
        show-header-overflow
        :tree-config="{
          children: 'childTree',
          expandAll: false,
        }"
        row-id="id"
        :use-virtual="true"
        border
      >
        <!-- :fixed="item.dataIndex === 'sortNum' || item.dataIndex === 'phaseCategory'" -->
        <u-table-column
          v-for="item in columns4"
          :key="item.dataIndex"
          :prop="item.dataIndex"
          :label="item.title"
          :width="item.width"
          :tree-node="item.dataIndex === 'phaseCategory'"
          align="center"
        >
          <template v-slot="{ row }">
            <span
              :title="row[item.dataIndex]"
              class="span-ellipsis"
            >
              <template v-if="row.nodeType === 0">
                <template v-if="['sortNum','phaseCategory','businessMatters','period','planStartTime','planEndTime','contractStartDate','contractEndDate'].includes(item.dataIndex)">
                  {{ row[item.dataIndex] }}
                </template>
              </template>
              <template v-else>
                <span
                  v-if="item.dataIndex === 'sortNum'"
                  :class="indexClass(row)"
                  class="sort-num"
                >
                  <img
                    v-if="row.promptLights === 1 || row.promptLights === 2"
                    :src="row.promptLights === 1 ? yellowLight : redLight"
                    width="20"
                    hight="20"
                  >
                  <span>{{ row[item.dataIndex] }}</span>
                </span>
                <template v-else-if="item.dataIndex === 'controlLevelId'">
                  {{ row.controlLevelName }}
                </template>
                <template v-else-if="item.dataIndex === 'directResPerList'">
                  {{ row[item.dataIndex].map(el=>el.label).join(',') }}
                </template>
                <a-switch
                  v-else-if="['isKeyNode','isMilestonesNode','isMainProcessNode','isVerticalTransportNode','isContractDurationNode'].includes(item.dataIndex)"
                  v-model="row[item.dataIndex]"
                  checked-children="是"
                  un-checked-children="否"
                  disabled
                />
                <span
                  v-else-if="item.dataIndex === 'feedback'"
                  :style="row[item.dataIndex] === '未反馈'?'color:red;':''"
                >
                  {{ row[item.dataIndex] }}
                </span>
                <template v-else>
                  {{ row[item.dataIndex] }}
                </template>
              </template>
            </span>
          </template>
        </u-table-column>
      </u-table>
    </a-spin>
    <!-- 甘特图 -->
    <GanttModal
      :visible.sync="ganttVisible"
      :data="ganttData"
    />
    <!-- 甘特图 -->
  </div>
</template>
<script>
import { columns4, nodeControlLevelList, feedBackList, nodeStatusList } from '../model.js'
import contractor from '@/api/construction/contractor'
import { UTable, UTableColumn } from 'umy-ui'
import GanttModal from '@/components/GanttModal'
import UploadList from '../../progress/file'
export default {
  name: 'PlanBoardDetail',
  props: {
    visible: {
      type: Boolean,
      require: true
    }
  },
  components: {
    UTable,
    UTableColumn,
    GanttModal,
    UploadList
  },
  data() {
    return {
      // 加载
      loading: false,
      // 代号网络图
      fileList: [],
      // 表格信息
      tableInfo: {
        projectName: void 0,
        nodeTotalNum: void 0,
        firstNodeNum: void 0,
        secondNodeNum: void 0,
        threeNodeNum: void 0,
        periodDay: void 0,
        periodDate: void 0
      },
      // 表头
      columns4,
      // 红灯
      redLight: require('@/assets/icons/redLight.png'),
      // 黄灯
      yellowLight: require('@/assets/icons/yellowLight.png'),
      // 表格数据
      tableData: [],
      // 甘特图显示隐藏
      ganttVisible: false,
      // 甘特图数据
      ganttData: {
        list: [],
        lines: [],
        startDate: '',
        endDate: ''
      },
      // 搜索表单
      searchForm: {},
      // 是否搜索
      isSearch: false,
      // 节点管控级别列表
      nodeControlLevelList,
      // 责任人反馈列表
      feedBackList,
      // 节点状态列表
      nodeStatusList
    }
  },
  watch: {
    visible: {
      handler(v) {
        if (v) {
          this.loadData()
          this.searchFiles()
        }
      }
    },
    // 表格数据监听
    tableData: {
      handler(list) {
        if (this.$refs.table) {
          // 获取之前展开数据
          const expandRecords = this.$refs.table.getTreeExpandRecords()
          // 获取之前滚动高度(表格实例上的scrollTop属性，在滚动到底部时会小于真实的scrollTop值，因此直接从dom获取真实滚动高度)
          const scrollTop = this.$refs.table.tableExample().bodyWrapper.scrollTop
          const scrollLeft = this.$refs.table.tableExample().bodyWrapper.scrollLeft
          // 加载数据
          this.$refs.table.reloadData(list).then(() => {
            // 是搜索默认展开全部
            if (this.isSearch) {
              this.$refs.table.setAllTreeExpansion()
              this.isSearch = false
            } else {
              // 数据加载完成出现之后，打开之前的展开行
              expandRecords.forEach((row) => {
                this.$refs.table.setTreeExpansion(row, true)
              })
            }
            // 还原之前滚动高度
            this.$refs.table.pagingScrollTopLeft(scrollTop + 1, scrollLeft)
            this.$nextTick(()=>{
              // 不加这一步，列表操作栏 会变形
              this.$refs.table.pagingScrollTopLeft(scrollTop, scrollLeft)
            })
          })
          // 扁平化树为甘特图数据
          let arr = []
          let lines = []
          const flatTree = (list) => {
            for (let i = 0; i < list.length; i++) {
              const obj = this.$clone(list[i])
              delete obj.childTree
              const { id: taskId, planStartTime: startDate, planEndTime: endDate, businessMatters, phaseCategory, statusLights, isKeyNode, nodeType } = obj
              const text = nodeType === 1 ? businessMatters : phaseCategory
              if (list[i].childTree) {
                flatTree(list[i].childTree)
              } else {
                obj.phaseCategory = text
                if (obj.frontConnectList && obj.frontConnectList.length > 0) {
                  lines = lines.concat(obj.frontConnectList)
                }
              }
              let color = ''
              const c = {
                0: 'class-slider-0',
                1: 'class-slider-1',
                2: 'class-slider-2',
                3: 'class-slider-3',
                4: 'class-slider-4'
              }
              // 甘特图颜色
              if (isKeyNode) {
                color = 'class-slider-key'
              } else if (this.$route.query.status + '' === '2') {
                color = c[statusLights]
              } else {
                color = 'class-slider-0'
              }
              arr.push({
                taskId,
                startDate,
                endDate,
                class: color,
                text,
                ...obj
              })
            }
          }
          flatTree(this.tableData)
          this.ganttData.list = arr.sort((a, b) => a.sortNum - b.sortNum)
          this.ganttData.lines = lines
        }
      }
    }
  },
  methods: {
    /**
     * @description: 获取文件列表
     * @param {void}
     * @return {void}
     */
    searchFiles() {
      contractor.doubleNetworkPictureQuery(this.$route.query.planId).then((res) => {
        if (res.code === 200) {
          this.fileList = res.data
        } else {
          this.fileList = []
        }
      })
    },
    /**
     * @description: 刷新
     * @return {void}
     */
    refresh(){
      this.loadData()
      this.$emit('synchronousUpdate')
    },
    /**
     * @description: 表格数据加载方法
     * @param {boolean} isSearch 是否搜索
     * @return {Promise} 接口Promise
     */
    async loadData(isSearch = false) {
      try {
        this.loading = true
        if (isSearch) {
          this.isSearch = isSearch
        }
        const {
          code,
          data: { projectName, nodeTotalNum, firstNodeNum, secondNodeNum, threeNodeNum, periodDay, planStartTime, planEndTime, treeListVO }
        } = await contractor.contractPlanDetailSearch(this.getSearchParms())
        if (code === 200) {
          this.tableInfo = {
            projectName,
            nodeTotalNum,
            firstNodeNum,
            secondNodeNum,
            threeNodeNum,
            periodDay,
            periodDate: (planStartTime ?? '' !== '') && (planEndTime ?? '' !== '') ? planStartTime + '--' + planEndTime : '--'
          }
          this.tableData = treeListVO
        } else {
          this.tableData = []
        }
      } catch (error) {
        console.log(error)
        return Promise.reject(error)
      } finally {
        this.loading = false
      }
    },
    /**
     * @description: 刷新
     * @return {void}
     */
    handleRefresh() {
      this.loadData()
    },
    /**
     * @description: 获取搜索参数
     * @return {Object}
     */
    getSearchParms() {
      let planStartOrigin = void 0,
        planStartOver = void 0,
        planEndOrigin = void 0,
        planEndOver = void 0,
        actualCompleteOrigin = void 0,
        actualCompleteOver = void 0
      if (Array.isArray(this.searchForm?.planStart) && this.searchForm.planStart.length>0) {
        planStartOrigin = this.searchForm.planStart[0].format('YYYY-MM-DD')
        planStartOver = this.searchForm.planStart[1].format('YYYY-MM-DD')
      }
      if (Array.isArray(this.searchForm?.planEnd) && this.searchForm.planEnd.length>0) {
        planEndOrigin = this.searchForm.planEnd[0].format('YYYY-MM-DD')
        planEndOver = this.searchForm.planEnd[1].format('YYYY-MM-DD')
      }
      if (Array.isArray(this.searchForm?.completeDate) && this.searchForm.completeDate.length>0) {
        actualCompleteOrigin = this.searchForm.completeDate[0].format('YYYY-MM-DD')
        actualCompleteOver = this.searchForm.completeDate[1].format('YYYY-MM-DD')
      }
      const { businessMatters, isVerticalTransportNode, nodeControl, feedBack, workStatus } = this.searchForm
      return {
        businessMatters,
        feedBack,
        isVerticalTransportNode: isVerticalTransportNode !== undefined ? JSON.parse(isVerticalTransportNode) : isVerticalTransportNode,
        nodeControl,
        planEndOrigin,
        planEndOver,
        planId: this.$route.query.planId + '',
        planStartOrigin,
        planStartOver,
        actualCompleteOrigin,
        actualCompleteOver,
        workStatus
      }
    },
    /**
     * @description: 重置搜索
     * @return {void}
     */
    handleReset() {
      this.searchForm = {}
      this.loadData()
    },
    /**
     * @description: 索引类名
     * @param {object} row 行数据
     * @return {string}
     */    
    indexClass(row){
      return row.promptLights === 1 || row.promptLights === 2 ? '': 'class-' + row.statusLights
    }
  }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
.plan-board-detail {
  margin-top: 15px;
}
.btn-wrapper {
  margin: 0 -5px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  >button, >span, >div{
    margin: 5px;
  }
}
.pub-table-select-count {
  > span {
    margin-right: 12px;
  }
}
.sort-num {
  display: block;
  display: flex;
  justify-content: center;
  align-items: center;
  img {
    margin-right: 5px;
    width: 16px;
    height: 16px;
  }
}
.class-0, .class-1, .class-2, .class-3, .class-4{
  color: #fff;
}
.class-0 {
  // background-color: #d1d1d1;
  color: #606266;
}
.class-1 {
  color: #606266;
}
.class-2 {
  background-color: #f85c62;
}
.class-3 {
  background-color: #1dc682;
}
.class-4 {
  background-color: #ffced0;
}

.plan-board-detail-search {
  margin-bottom: 10px;
  @{deep} .ant-form-item .ant-form-item-label {
    width: 0;
  }
  @{deep} .ant-form-item .ant-form-item-control-wrapper {
    width: 100%;
  }
}
.plan-board-detail-search-width {
  width: 200px;
}
.plan-board-detail-search-date{
  width: 268px;
}
.activity-on-arrow{
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-left: 5px;
}
</style>
